package com.zhz.mall.common.constraints;

import com.zhz.mall.common.annotation.Mobile;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description: @mobile注解校验器
 * @motto: 代码源于生活，高于生活艺术
 * @author: zhouhengzhe
 * @date: 2023/1/12 14:25
 * @since 1.0
 **/
public class MobileValidator implements ConstraintValidator<Mobile, CharSequence> {

    private boolean required = false;

    /**
     * 验证手机号
     */
    private final Pattern pattern = Pattern.compile("^[1][3,4,5,6,7,8,9]\\d{9}$");

    /**
     * 在验证开始前调用注解里的方法，从而获取到一些注解里的参数
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(Mobile constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    /**
     * 判断参数是否合法
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     */
    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (this.required) {
            // 验证
            return isMobile(value);
        }
        if (StringUtils.hasText(value)) {
            // 验证
            return isMobile(value);
        }
        return true;
    }

    /**
     * 匹配电话号码
     * @param value
     * @return
     */
    private boolean isMobile(CharSequence value) {
        Matcher m = pattern.matcher(value);
        return m.matches();
    }

}
